import * as crypto from 'crypto'

// 硬编码至代码中, 开启SK加密后，应用开发平台秘钥作为实际秘钥的分片
const SK_PART = 'Lyb7rGEmrGsI0RRkGtSPfUIvzyenpOk3'
// AES-CBC解密函数
function cbcDecrypt(encryptedData: Buffer, key: string, iv: string) {
    // 将key和iv从字符串转换为Buffer（字节数组）
    const keyBuffer = Buffer.from(key, 'utf8')
    const ivBuffer = Buffer.from(iv, 'utf8')

    // 创建AES-CBC解密器
    const decipher = crypto.createDecipheriv('aes-128-cbc', keyBuffer, ivBuffer)

    // 解密数据（输入为Hex格式）
    let decrypted = Buffer.concat([decipher.update(encryptedData), decipher.final()])

    // 获取填充的字节数
    const padding = decrypted[decrypted.length - 1]

    // 去除填充部分
    if (padding > 0 && padding <= 16) {
        decrypted = decrypted.slice(0, -padding)
    }

    return decrypted.toString('utf8')
}

function getContentHash(content: string) {
    return crypto.createHash('sha256').update(content).digest('hex')
}


export function getSK() {
    const ak = process.env.AK
    let sk = ''

    if (!process.env.SK_SALT) {
        sk = process.env.SK
    } else {
        try {
            let skSalt = process.env.SK_SALT
            const skSaltBuffer = Buffer.from(skSalt, 'base64')
            const key = getContentHash(SK_PART).slice(0, 16)
            const iv = getContentHash(ak).slice(0, 16)
            const appKeyByte = cbcDecrypt(skSaltBuffer, key, iv)
            sk = appKeyByte.toString()
        } catch (err) {
            throw new Error(`plugin SK decrypt error: ${err.message}`)
        }
    }
    return sk
}


export function ecisDecrypt(sk:string, enData:string) {
    const key = crypto.createHash('md5').update(sk).digest('hex');
    const iv = Buffer.from(key, 'utf8').slice(0,16).toString('utf8')
    const crypted = new Buffer(enData, 'base64').toString('binary');
    var decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
    var decoded = decipher.update(crypted, 'binary', 'utf8');
    decoded += decipher.final('utf8');
    return decoded;
}
